var debounce = function (idle, action) {
  var last;
  return function () {
    var ctx = this, args = arguments;
    clearTimeout(last);    //如果在timeout内调用, 则清除timeout重新计时
    last = setTimeout(function () {
      action.apply(ctx, args);
    }, idle);
  }
};

var formatJson = function (obj, indent) {
  !indent && (indent = 0);
  if(obj === null) return null;
  if(typeof obj === 'string') return "\"" +obj + "\"";
  if(typeof obj !== 'object') return obj;
  var isArray =obj instanceof Array;
  var value = isArray ? '[\n' : '{\n';
  var padding = generatePadding(indent);
  var key;
  for(var i in obj) {
      key = isArray ? "" : '"' + i + '": ';
      value += padding+'  ' + (key + formatJson(obj[i], indent + 2)) + ",\n";
  }
  if(value.length > 2) {
      value = value.substring(0,value.length - 2) + '\n';
      value += (padding +  (isArray ? ']' : '}'));
  } else {
      value = isArray ? '[]': '{}';
  }
  return value;
};

function generatePadding(num){
    var str = '';
    while(num--) str+= ' ';
    return str;
}

$(document).ready(function () {

  $('.nav-links').each(function () {
    if ($(this).attr('href') === location.pathname) {
      $(this).parent().addClass('active');
    }
  });

  $('.redirect-hash').click(function () {
    var target = $(this).attr('data-target');
    location.href = location.href.split("#")[0] + '#'+ target;
  });

  $('#wordInput').keydown(function (e) {
    if (e.keyCode === 13) {
      searchWord($(this).val().trim());
    }
  });

  $('#searchBtn').click(function () {
    searchWord($('#wordInput').val().trim());
  });

  $('#export').click(function () {
    $('#exportModal').modal();
  });

  $('#sureExport').click(function () {
    var type = $("[name='optionsRadios']:checked").val();
    window.open('/export?type='+ type);
    $('#exportModal').modal('hide');
  });

  function searchWord(word) {
    if (word) {
      if(location.pathname === '/') {
        window.getData && window.getData(word);
        $('#wordInput').val('');
      } else {
        location.href = '/#word='+word;
      }
    }
  }
});